
// tslint:disable
import { config } from 'rxjs';
import { Component, Input, OnInit } from '@angular/core';
import { AlertController, ModalController } from "@ionic/angular";
import { ComItem } from 'src/app/route/entry/com-item';
import { ActionSheetService, Modal, zh_CN } from "ng-zorro-antd-mobile";
import { FormGroup } from '@angular/forms';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { RankingModalComponent } from "../ranking-modal/ranking-modal.component";
import { SharePageComponent } from "../share-page/share-page.component";
@Component({
  selector: 'app-nested-form-tag',
  templateUrl: './nested-form-tag.component.html',
  styleUrls: ['./nested-form-tag.component.scss'],
})
export class NestedFormTagComponent implements OnInit {
  @Input() titleTagData: any;
  @Input() formTagData: any;
  @Input() buttonTagData: any;
  @Input() pageParams: any;
  @Input() tags: any = [];
  headerTags: any = [];
  footerTags: any = [];
  contentTags: any = [];
  clickOuterDismiss = true; // 弹窗表单 false 外不消失
  // 标签头数据
  titleBar: any = {};
  isGrayBg = false; // 默认背景为灰色
  isPageDisabled = false;
  backgroundImg: string; // 头部背景图片
  showWaterImg = false; // 是否显示水印
  showRefresher = false; // 是否可以下拉刷新
  showLoading = false; // 是否展示上拉动画
  @Input() pageData: any;  // page 接口返回的所有数据
  @Input() cssClass: any; // //  配置 <param name="modalCss" value="bottom"></param> 不配置全屏，bottom 底部弹出，其他值 居中

  @Input() cssStyle: any; // 改变默认小窗样式用 link.cssStyle  或者 link.params.cssStyle,
  // 分享页面数据
  shareData = {
    icon: "share.png",
    layout: "right",
    submit: {
      content: {},
      id: "string",
    },
  };
  constructor(
    public modalController: ModalController,
    private http: HttpService,
    public appGlobalService: AppGlobalService,
    public alertController: AlertController,

  ) { }
  ngOnInit() {
    let pageData: any;
    if (this.pageData) {
      if (typeof (this.pageData) === 'object') {
        pageData = this.pageData;
      } else {
        pageData = JSON.parse(this.pageData.script);
      }
      this.parsePageData(pageData);
    } else if (this.pageParams) {
      if ((this.pageParams.params.clickOuterDismiss === undefined) || (this.pageParams.params.clickOuterDismiss === "true")) {
        this.clickOuterDismiss = true;
      } else {
        this.clickOuterDismiss = false;
      }

      this.http.post('application/page', this.pageParams, async res => {
        pageData = JSON.parse(res.script);
        this.parsePageData(pageData);
      });
    }
  }
  parsePageData(pageData) {
    this.titleBar =
      (JSON.stringify(pageData.titleBar) !== undefined && JSON.stringify(pageData.titleBar) !== '{}') ? pageData.titleBar : undefined;
    this.backgroundImg = this.titleBar && this.titleBar.background ?
      'url("' + this.titleBar.background + '") no-repeat center' : undefined;
    this.showWaterImg = pageData.showWaterImg;
    this.tags = pageData.views === undefined ? pageData.tags : pageData.views[0].tags;
    if (this.tags !== undefined) {
      this.managerTags(this.tags);
    } else {
      // 1.9.13 改动版本新增参数用于 一键登录 手机快捷登录 账号密码登录
      this.tags = [pageData];
      // this.tags.push(pageData);
    }
    setTimeout(() => {
      // 
      if (this.cssClass === 'customHeightPage') {
        const allH = document.getElementById('full-screen-modal').offsetHeight;
        let headerH = document.getElementById('full-screen-modal-header') ? document.getElementById('full-screen-modal-header').offsetHeight : 0;
        let footerH = document.getElementById('full-screen-modal-footer') ? document.getElementById('full-screen-modal-footer').offsetHeight : 0;
        if (document.getElementById('full-screen-modal-content') !== undefined) {
          const contentH = `height:` + (allH - headerH - footerH) / 16.0 + `rem`;
          document.getElementById('full-screen-modal-content').setAttribute('style', contentH)
        }

      }

    }, 200);
  }
  managerTags(tags) {
    tags.forEach(element => {
      if (element.linearLayout === 'body') {
        this.contentTags.push(element);
      } else if (element.linearLayout === 'footer') {
        this.footerTags.push(element);
      } else if (element.linearLayout === 'header') {
        this.headerTags.push(element);
      } else {
        this.contentTags.push(element);
      }
    });
  }

  onCancelClick(e) {
    e.stopPropagation();
  }
  dismissClick() {
    if (this.clickOuterDismiss) {
      this.modalController.dismiss();
      if (this.pageParams
        && this.pageParams.params
        && this.pageParams.params.isRefreshAfterClickBackDrop) {
        setTimeout(() => {
          this.appGlobalService.reloadCurrentPage(0);
        }, 600);
      }
    } else {

    }

  }

  back() {
    this.modalController.dismiss();
  }

  // 确定提交表单用
  textButton(textButton) {
    console.log(textButton);
    this.check(textButton);
  }

  // 数组btn
  iconButtonClick(item) {
    this.selectItem(item);
  }

  selectItem(item) {
    if (item.action === "submit") {
      item.submit.sessionId = localStorage.getItem("sessionId");
      console.log("more --> submit", item.submit);
      this.http.post("application/submit", item.submit, (res) => {
        this.appGlobalService.showToast(res.message, 2000, "middle");
      });
    } else if (item.action === "link") {
      const param = {
        pageId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem("sessionId"),
      };
      this.appGlobalService.goToForward(param);
    } else if (item.action === "question") {
      // alert
      this.question(item);
    } else if (item.action === "prompt") {
      // 弹出输入框 alert
      this.inputAlert(item);
    } else if (item.action === "modal") {
      this.openRankingModal("ranking-modal", item);
    } else if (item.action === "view") {
      const param = {
        viewId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem("sessionId"),
      };
      this.appGlobalService.goToForward(param);
    } else if (item.action = 'share') {
      this.share(item.link);
    }
  }
  /** 分享 */
  share(link) {
    console.log("share --> page", link);
    // 请求参数
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: link.target,
      params: link.params,
    };
    this.http.post("application/page", params, (res) => {
      this.shareData = JSON.parse(res.script).views[0].tags[0].data;
      this.presentModal();
    });
  }

  // 分享弹框
  async presentModal() {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: "sharePage",
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: this.shareData },
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  // ranking-modal
  async openRankingModal(className, item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.link.target,
      params: item.link.params,
    };
    this.http.post("application/page", params, async (res) => {
      const tagData = JSON.parse(res.script).views[0].tags[0].data;
      // "ranking-modal"
      const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: className,
        component: RankingModalComponent,
        componentProps: { tagData },
      });
      await modal.present();
      // 监听销毁的事件
      const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    });
  }

  inputAlert(item) {
    const that = this;
    Modal.prompt(
      item.htmlObj.title,
      "",
      [
        {
          text: item.htmlObj.buttonLabel,
          onPress: (value) =>
            new Promise<void>((resolve, reject) => {
              if (value.length === 0 || that.appGlobalService.isPhone(value)) {
                resolve();
                item.submit.content[item.htmlObj.input.formKey] = value;
                item.submit.sessionId = localStorage.getItem("sessionId");
                console.log("more --> submit", item.submit);
                that.http.post("application/submit", item.submit, (res) => {
                  if (res.message) {
                    this.appGlobalService.showToast(
                      res.message,
                      2000,
                      "middle"
                    );
                  }
                });
              } else {
                that.appGlobalService.showToast(
                  "请输入正确的号码",
                  2000,
                  "top"
                );
              }
            }),
        },
      ],
      "default",
      null,
      [item.htmlObj.input.placeholder]
    );
  }

  check(item) {
    console.log(item.action);
    const keyString: string = item.paramName;
    let keys = keyString ? keyString.split(',') : [];
    // if (!keys) {
    //   return;
    // }
    if (item.action === 'reset') {

      keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);

        if (formGroup) {
          formGroup.reset();
        }
      });

    } else if (item.action === 'submit') {
      const keyString: string = item.paramName;
      keys = keyString.split(',');
      let count = 0;
      let formCount = 0;
      keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);
        const messageObj = this.appGlobalService.getFormGroupMessageWithParamName(element);
        const compareArray = this.appGlobalService.getFormCompareWithParamName(element);
        if (formGroup && messageObj) {
          formCount += 1;
          this.valid(formGroup, messageObj, compareArray, params => {
            if (params) {
              item.submit.content[element] = params;
              count += 1;
            } else {
              return;
            }
          });
        }
      });
      // 全部校验通过
      if (count === formCount) {
        item.submit.sessionId = localStorage.getItem('sessionId');

        console.log('check --> submit', item.submit);
        this.http.post('application/submit', item.submit, res => {
          // 请求成功
          if (res.success) {
            this.success(res, item);
          } else {
            // 请求数据失败
            this.appGlobalService.showToast(res.message, 2000, 'middle');
          }
        });
      }

    } else if (item.action === 'link') {
      const param = {
        pageId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      this.appGlobalService.goToForward(param);

    } else if (item.action === 'question') {
      // alert
      this.question(item);
    }
  }
  // alert
  async question(item) {
    const that = this;
    const alert = await this.alertController.create({

      header: '',
      subHeader: '',
      message: item.question,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          item.submit.sessionId = localStorage.getItem('sessionId');
          console.log('more --> submit', item.submit);
          this.http.post('application/submit', item.submit, res => {
            // 刷新当前页面
            if (item.submit.content.back && item.submit.content.back === '0') {
              this.http.reloadCurrentPage();
              setTimeout(() => {
                localStorage.setItem('needRefresh', 'true');
                this.appGlobalService.showToast(res.message, 2000, 'middle');
              }, 1000);
            } else {
              this.appGlobalService.showToast(res.message, 2000, 'middle');
            }
          });
        }
      }]
    });
    await alert.present();

  }
  success(res, item) {
    if (res.message) {
      this.appGlobalService.showToast(res.message, 2000, 'middle');
      this.modalController.dismiss({ data: true });
    }
    if (item.link && item.link.type === 'page') {

      const link = {
        pageId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      // to newPage
      this.appGlobalService.goToForward(link);

    } else if (res.target && res.type === 'updateItem') {
      const link = {
        pageId: res.target,
        params: res.params ? res.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      this.modalController.dismiss({ data: link });

    } else if (res.target && res.type === 'page') {

      const link = {
        pageId: res.target,
        params: res.params ? res.params : {},
        sessionId: localStorage.getItem('sessionId')
      };

      this.appGlobalService.goToForward(link);
    }
  }

  valid(formGroup: FormGroup, allLabel, compareArray, callback: Function) {
    if (formGroup.valid) {
      // console.log(this.formGroup.value);
      const params = formGroup.value;
      for (const prop in params) {
        if (Array.isArray(params[prop])) {
          params[prop] = params[prop].join(',');
        }
        // 删除无效值
        if (prop === '') {
          // delete params[prop];
        }
        if (prop.indexOf('samekey_') > -1) {
          const p = prop.replace('samekey_', '');
          params[p] = params[prop] ? params[prop] : "";
          delete params[prop];
        }
      }
      let compare = true;
      for (let index = 0; index < compareArray.length; index++) {
        const compareItem = compareArray[index];
        if (Number(params[compareItem.minKey]) > Number(params[compareItem.maxKey])) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.lessTip && compareItem.lessTip.length > 0) {
            this.appGlobalService.showToast(compareItem.lessTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }

          compare = false;
          break;
        } else if (Number(params[compareItem.minKey]) === Number(params[compareItem.maxKey]) && Number(params[compareItem.minKey]) != 0) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.canEqual) {
            continue
          } else if (compareItem.equalTip && compareItem.equalTip.length > 0) {
            this.appGlobalService.showToast(compareItem.equalTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }

          compare = false;
          break;
        }
      }
      if (compare) {
        console.log(params);
        callback(params);
      }
      // this.onReset();
    } else {
      this.getErrors(formGroup, allLabel);
    }
  }

  getErrors(form, allLabel) {
    const errs = [];
    for (const name in form.controls) {
      // eg: controls[name] = phone
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }
    if (errs.length) {
      const errItem = errs[0];

      const firstErrMsgKey = Object.keys(errItem.err)[0];
      console.log(errItem.key, '校验的字段名');
      const messageObj = allLabel[errItem.key];
      const showMessage = messageObj[firstErrMsgKey];
      this.appGlobalService.showToast(showMessage, 3000, 'top');

    }
  }

}
